<?php


namespace app\index\controller\wanlshop;


use app\api\model\wanlshop\Withdraw;
use app\common\controller\Wanlshop;
use app\common\model\wanlshop\Settlement;
use think\Validate;

class Account extends Wanlshop
{
    protected $model = null;
    protected $noNeedLogin = '';
    protected $noNeedRight = '*';
    public function _initialize()
    {
        parent::_initialize();

    }

    //账户统计
    public function index(){
        $user_id = $this->auth->id;
        $shop_id = $this->shop->id;
        $date      = $this->request->post('date', date('Y-m-d 00:00:00',time()-6*86400).' - '.date('Y-m-d 23:59:59'));
        $data      = $this->getOrderStatisticsData($date);
        $earninglist = $spendinglist = [];
        foreach ($data as $day)
        {
            $starttime   = strtotime($day['starttime']);
            $endtime     = strtotime($day['endtime']);
            $columns[]   = $day['column'];
            $earninglist[] = Settlement::where([
                'shop_id'=>$shop_id,
                'status'=>'success',
                'price'=>['>',0]
            ])->where('createtime','between', [$starttime,$endtime])->sum('price');
            $spendinglist[] = Settlement::where([
                'shop_id'=>$shop_id,
                'status'=>'success',
                'price'=>['<',0]
            ])->where('createtime','between', [$starttime,$endtime])->sum('price');
        }
        $statistics = [
            'columns'   => $columns,
            'earninglist'   => $earninglist,
            'spendinglist'   => $spendinglist,
        ];
        if ($this->request->isPost()) {
            $this->success('', '', $statistics);
        }


        $withdrawSum = Withdraw::where(['user_id'=>$user_id,'status' => 'successed'])->sum('money');
        $settlementSum = Settlement::where(['shop_id'=>$shop_id,'status'=>'success'])->sum('price');
        $banklist = model('app\api\model\wanlshop\PayAccount')
            ->where(['user_id' => $user_id])
            ->order('createtime desc')
            ->select();
        $this->assign([
            'withdrawSum' => $withdrawSum, // 提现金额
            'settlementSum' => $settlementSum, // 结算金额
            'date' => $date,
            'banklist' => $banklist,
        ]);
        $this->assignconfig( ['statistics' => $statistics]);
        return $this->view->fetch();
    }

    //个人资料修改
    public function profile(){
        $this->view->assign('title', __('Profile'));
        return $this->view->fetch();
    }


    /**
     * 修改密码
     */
    public function changepwd()
    {


        if ($this->request->isPost()) {
            $oldpassword = $this->request->post("oldpassword");
            $newpassword = $this->request->post("newpassword");
            $renewpassword = $this->request->post("renewpassword");
            $token = $this->request->post('__token__');
            $rule = [
                'oldpassword'   => 'require|length:6,30',
                'newpassword'   => 'require|length:6,30',
                'renewpassword' => 'require|length:6,30|confirm:newpassword',
                '__token__'     => 'token',
            ];

            $msg = [
                'renewpassword.confirm' => __('Password and confirm password don\'t match')
            ];
            $data = [
                'oldpassword'   => $oldpassword,
                'newpassword'   => $newpassword,
                'renewpassword' => $renewpassword,
                '__token__'     => $token,
            ];
            $field = [
                'oldpassword'   => __('Old password'),
                'newpassword'   => __('New password'),
                'renewpassword' => __('Renew password')
            ];
            $validate = new Validate($rule, $msg, $field);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
                return false;
            }

            $ret = $this->auth->changepwd($newpassword, $oldpassword);
            if ($ret) {
                $this->success(__('Reset password successful'), url('user/login'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        $this->view->engine->layout(false);
        $this->view->assign('title', __('Change password'));
        return $this->view->fetch();
    }

    // 提现账户
    public function bank(){
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            $list = model('app\api\model\wanlshop\PayAccount')
                ->where(['user_id' => $this->auth->id])
                ->order('createtime desc')
                ->select();
            $result = array("total" => count($list), "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    // 添加账户
    public function bankadd(){
        $bankcode = [
            'ALIPAY'=> '支付宝账户',
            'WECHAT'=> '微信账户',
            'ICBC'=> '工商银行',
            'ABC'=> '农业银行',
            'PSBC'=> '邮储银行',
            'CCB'=> '建设银行',
            'CMB'=> '招商银行',
            'BOC'=> '中国银行',
            'COMM'=> '交通银行',
            'SPDB'=> '浦发银行',
            'GDB'=> '广发银行',
            'CMBC'=> '民生银行',
            'PAB'=> '平安银行',
            'CEB'=> '光大银行',
            'CIB'=> '兴业银行',
            'CITIC'=> '中信银行'
        ];
        $this->view->assign('bankList', build_select('bankCode', $bankcode, '', ['class' => 'form-control selectpicker selectpicker-bank']));
        return $this->view->fetch();
    }
    // 删除账户
    public function bankdel($ids){

        $row = model('app\api\model\wanlshop\PayAccount')
            ->where('id', 'in', $ids)
            ->where(['user_id' => $this->auth->id])
            ->delete();
        if($row){
            $this->success('操作成功', $row);
        }else{
            $this->error(__('删除失败'));
        }
    }

    //提现记录
    public function withdrawlist(){
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = model('app\api\model\wanlshop\Withdraw')
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
}